package com.notify;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.Toast;

public class Tools extends Application {

	private String myState;

	public void saveData(Context con, String variable, String data) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(con);
		prefs.edit().putString(variable, data).commit();
	}

	public String getData(Context con, String variable, String defaultValue) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(con);
		String data = prefs.getString(variable, defaultValue);
		return data;
	}

	public String Autologin(Context con) {
		Tools tools = new Tools();

		String username = tools.getData(con, con.getString(R.string.username),
				"");
		String password = tools.getData(con, con.getString(R.string.password),
				"");
		String server = tools.getData(con, con.getString(R.string.server), "");
		String status = "";

		server = server.replaceAll("\\s+", "");

		if (server.equals(""))
			return "no";

		try {
			XMLParser parser = new XMLParser();
			String xml = parser.getXmlFromUrl(server
					+ "?action=login&username=" + username + "&password="
					+ password); // getting XML
			Document doc = parser.getDomElement(xml); // getting DOM element
			NodeList nl = doc.getElementsByTagName(con
					.getString(R.string.key_item));
			Element e = (Element) nl.item(0);
			status = parser.getValue(e, con.getString(R.string.status));

		} catch (Exception e) {
			Toast.makeText(con, "Error auto-login", Toast.LENGTH_LONG).show();
		}

		return status;

	}

	public String login(String username, String password, String server,
			Context con) {
		String status = "";

		try {

			XMLParser parser = new XMLParser();

			String xml = parser.getXmlFromUrl(server
					+ "?action=login&username=" + username + "&password="
					+ password); // getting XML

			Document doc = parser.getDomElement(xml);

			NodeList nl = doc.getElementsByTagName(con
					.getString(R.string.key_item));

			Element e = (Element) nl.item(0);

			status = parser.getValue(e, con.getString(R.string.status));

		} catch (Exception e) {
			Toast.makeText(con, "Error login", Toast.LENGTH_LONG).show();
		}

		return status;

	}

	public String getState() {
		return myState;
	}

	public void setState(String s) {
		myState = s;
	}

}
